//
//  EncryptedFileURLProtocol.m
//
//  Created by Robin Summerhill on 15/07/2010.
//  Copyright 2010 Aptogo Ltd. All rights reserved.
//
//  Permission is given to use this source code file without charge in any
//  project, commercial or otherwise, entirely at your risk, with the condition
//  that any redistribution (in part or whole) of source code must retain
//  this copyright and permission notice. Attribution in compiled projects is
//  appreciated but not required.
//

#import "EncryptedFileURLProtocol.h"
#import "NSDataEncrypt.h"

// Default 256bit key - change this!
static NSString *sharedKey = @"123456";

@interface EncryptedFileURLProtocol ()
@property (strong,nonatomic) NSURLConnection *connection;
@end
@implementation EncryptedFileURLProtocol

+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    NSString *path = [[request URL]path];
    NSString *app = @"/app/";
    NSRange foundObj=[path rangeOfString:app options:NSCaseInsensitiveSearch];
    if(foundObj.length>0 && ![NSURLProtocol propertyForKey:NSStringFromClass([self class])
                                                 inRequest:request]) {
        return YES;
    }
    return NO;
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
    return request;
}

+ (void)setKey:(NSString *)key
{
    if (key != sharedKey)
    {
        sharedKey = [key copy];
    }
}

+ (NSString*)key
{
    return sharedKey;
}

// Called when URL loading system initiates a request using this protocol. Initialise input stream, buffers and decryption engine.
- (void)startLoading
{
    NSMutableURLRequest *newRequest = [self.request mutableCopy];
    [NSURLProtocol setProperty:@YES
                        forKey:NSStringFromClass([self class])
                     inRequest:newRequest];
    self.connection = [NSURLConnection connectionWithRequest:newRequest delegate:self];
}

// Called by URL loading system in response to normal finish, error or abort. Cleans up in each case.
- (void)stopLoading
{
//     NSLog(@"stopLoading%@",self.request);
}

- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response {
    [self.client URLProtocol:self
          didReceiveResponse:response
          cacheStoragePolicy:NSURLCacheStorageNotAllowed];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    //[self.comeontomdata  appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSData *data2 = [NSData dataWithContentsOfURL:self.request.URL];
    [self.client URLProtocol:self didLoadData:[data2 aesDecrypt:[sharedKey md5Data]]];
//    NSLog(@"comeontom:%@",[[NSString alloc]initWithData:[data2 aesDecrypt:[sharedKey md5Data]] encoding:NSUTF8StringEncoding] );
    [self.client URLProtocolDidFinishLoading:self];
    self.connection = nil;
}
@end
